package com.zian.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zian.context.BaseContext;
import com.zian.domain.dto.GoodsInfoDTO;
import com.zian.domain.dto.PageDTO;
import com.zian.domain.po.SysGoodsCategory;
import com.zian.domain.po.SysGoodsInfo;
import com.zian.domain.query.GoodsQuery;
import com.zian.domain.vo.GoodsInfoVO;
import com.zian.domain.vo.GoodsQueryVO;
import com.zian.enums.GoodsSellStatusEnum;
import com.zian.exception.BadRequestException;
import com.zian.exception.DbException;
import com.zian.mapper.SysGoodsCategoryMapper;
import com.zian.mapper.SysGoodsInfoMapper;
import com.zian.service.ISysGoodsInfoService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author
 * @since 2024-09-08
 */
@Service
@RequiredArgsConstructor
public class SysGoodsInfoServiceImpl extends ServiceImpl<SysGoodsInfoMapper, SysGoodsInfo> implements ISysGoodsInfoService {
    private final SysGoodsCategoryMapper sysGoodsCategoryMapper;

    @Override
    public PageDTO<GoodsQueryVO> queryGoodsInfoPage(GoodsQuery query) {
        Page<GoodsQueryVO> page = query.toMpPage();
        List<GoodsQueryVO> list = getBaseMapper().queryGoodsInfoPage(page, query);
        if (CollUtil.isEmpty(list)) return PageDTO.empty(0L, 0L);
        return PageDTO.of(page, list);
    }

    @Override
    public GoodsInfoVO queryGoodsInfoDetail(Long id) {
        SysGoodsInfo goodsInfo = getById(id);
        GoodsInfoVO vo = BeanUtil.toBean(goodsInfo, GoodsInfoVO.class);
        SysGoodsCategory category = sysGoodsCategoryMapper.selectById(vo.getGoodsCategoryId());
        if (category != null) {
            List<Integer> ancestors = category.getAncestors();
            // 处理分类树形结构
            ancestors.remove(0);
            ArrayList<Integer> categoryIds = new ArrayList<>(ancestors);
            categoryIds.add(category.getId().intValue());
            vo.setCategoryIds(categoryIds);
        } else {
            vo.setCategoryIds(Collections.emptyList());
        }

        if (goodsInfo == null) throw new BadRequestException("商品不存在");
        return vo;
    }

    @Override
    @Transactional
    public void deleteGoodsInfoByIds(List<Long> ids) {
        if (CollUtil.isEmpty(ids)) throw new BadRequestException("参数错误");
        boolean b = removeByIds(ids);
        if (!b) throw new DbException("删除商品失败");
    }

    @Override
    public void updateGoodsInfo(GoodsInfoDTO dto) {
        Long currentId = BaseContext.getCurrentId();
        SysGoodsInfo goodsInfo = getById(dto.getId());
        if (goodsInfo == null) throw new BadRequestException("商品不存在");
        SysGoodsInfo dbGoodsInfo = BeanUtil.toBean(dto, SysGoodsInfo.class);
        if (CollUtil.isEmpty(dto.getGoodsCarousel())) {
            ArrayList<String> list = new ArrayList<>();
            list.add(dto.getGoodsCoverImg());
            dbGoodsInfo.setGoodsCarousel(list);
        }
        dbGoodsInfo.setUpdateUser(currentId);
        boolean b = updateById(dbGoodsInfo);
        if (!b) throw new DbException("修改商品失败");
    }

    @Override
    public void addGoodsInfo(GoodsInfoDTO dto) {
        SysGoodsInfo one = lambdaQuery().eq(SysGoodsInfo::getGoodsName, dto.getGoodsName()).one();
        if (one != null) throw new BadRequestException("商品名已存在");
        SysGoodsInfo goodsInfo = BeanUtil.toBean(dto, SysGoodsInfo.class);
        if (CollUtil.isEmpty(goodsInfo.getGoodsCarousel())) {
            ArrayList<String> list = new ArrayList<>();
            list.add(dto.getGoodsCoverImg());
            goodsInfo.setGoodsCarousel(list);
        }
        Long currentId = BaseContext.getCurrentId();
        goodsInfo.setUpdateUser(currentId);
        goodsInfo.setCreateUser(currentId);
        boolean b = save(goodsInfo);

        if (!b) throw new DbException("新增商品失败");

    }

    @Override
    public void updateGoodsSellStatus(Long id) {
        Long currentId = BaseContext.getCurrentId();
        if (id == null) throw new BadRequestException("id 不能为空");
        SysGoodsInfo goodsInfo = getById(id);
        if (goodsInfo == null) throw new BadRequestException("商品不存在");
        GoodsSellStatusEnum goodsSellStatus = goodsInfo.getGoodsSellStatus();
        if (goodsSellStatus.equals(GoodsSellStatusEnum.SELLING)) {
            goodsInfo.setGoodsSellStatus(GoodsSellStatusEnum.STOP_SELLING);
        } else {
            goodsInfo.setGoodsSellStatus(GoodsSellStatusEnum.SELLING);
        }
        lambdaUpdate()
                .eq(SysGoodsInfo::getId, id)
                .set(SysGoodsInfo::getGoodsSellStatus, goodsInfo.getGoodsSellStatus())
                .set(SysGoodsInfo::getUpdateTime, LocalDateTime.now())
                .set(SysGoodsInfo::getUpdateUser, currentId)
                .update();
    }
}
